package models;

import siena.*;
import static utils.AppConstants.*;

/**
 * A class that represents a permission associated between some two users
 */
public class UserPermission extends Model {

	@Id(Generator.AUTO_INCREMENT)
	public long id;
	public User receiver;
	public User sender;
	public int permission;

	public UserPermission(User receiver, User sender, int permission) {
		super();
		this.receiver = receiver;
		this.sender = sender;
		this.permission = permission;
	}

	public int getPermission() {
		return permission;
	}

	public void setPermission(int permission) {
		this.permission = permission;
	}

	public Long getId() {
		return id;
	}

	public User getReceiver() {
		return receiver;
	}

	public User getSender() {
		return sender;
	}

	public static Query<UserPermission> all() {
		return Model.all(UserPermission.class);
	}

	public static int getPermission(String receiverMobile, String senderMobile) {
		// get the user of the receiverMobile
		User receiver = User.findByPhone(receiverMobile);
		User sender = User.findByPhone(senderMobile);
		UserPermission x = ((all(UserPermission.class).filter("receiver",
				receiver)).filter("sender", sender)).get();
		if (x == null) {
			x = new UserPermission(receiver, sender, ALWAYS_ASK);
			x.insert();
		}
		return x.permission;
	}
}
